package com.zhang.first.day04;

import com.zhang.first.utils.ClickEvent;
import com.zhang.first.utils.ClickEventSource;
import com.zhang.first.utils.UrlViewCountPerWindow;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

/**
 * 每个URL在每隔5秒钟的滚动窗口中被浏览的次数
 * @title:
 * @author: zhang
 * @date: 2022/1/17 20:00
 */
public class Example4 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new ClickEventSource())
                .keyBy(r -> r.url)
                .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
                .process(new ProcessWindowFunction<ClickEvent, UrlViewCountPerWindow, String, TimeWindow>() {
                    //时间到达窗口结束时间-1毫秒时，触发process的执行
                    @Override
                    public void process(String value, Context context, Iterable<ClickEvent> elements, Collector<UrlViewCountPerWindow> out) throws Exception {
                        Long count = 0L;
                        for (ClickEvent element : elements) count++;

                        out.collect(new UrlViewCountPerWindow(
                                value,
                                count,
                                context.window().getStart(),
                                context.window().getEnd()
                        ));
                    }
                })
                .print();

        env.execute();
    }
}
